package jjj.jjjjj;

import jdbc.DBUtil;
import jdbc.UserInfo;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

public class jj2 {
    public int insert(UserInfo userInfo) {
        // UserInfo userInfo= InputUtil.getInputObject(new UserInfo(),"注册功能","注册");
        try (Connection connection = DBUtil.getConnection()) {
            PreparedStatement ps =  connection.prepareStatement(
                    "INSERT INTO userinfo(username,password,nickname,age) " +
                        "VALUES(?,?,?,?)");
                ps.setString(1, userInfo.getUsername());
                ps.setString(2, userInfo.getPassword());
                ps.setString(3, userInfo.getNickname());
                ps.setInt(4, userInfo.getAge());
                return ps.executeUpdate();
            } catch (SQLException e) {
            e.printStackTrace();
        }

        return 0;
    }

    public UserInfo findByUsername(String  username) {

        try (Connection connection = DBUtil.getConnection()) {
            PreparedStatement ps = connection.prepareStatement(
                    "SELECT username,password " +
                    "FROM userinfo " +
                    "WHERE username=?");
            ps.setString(1,username);
            ResultSet rs = ps.executeQuery();
            if(rs.next()){
                UserInfo userInfo=new UserInfo();
                userInfo.setUsername(rs.getString("username"));
                userInfo.setPassword(rs.getString("password"));
                userInfo.setNickname(rs.getString("nickname"));
                userInfo.setAge(rs.getInt("age"));
                return userInfo;
            }

        } catch (SQLException e) {
            e.printStackTrace();
        }
        return null;
    }
    public int update(UserInfo userInfo){
        try(Connection connection=DBUtil.getConnection()) {
            PreparedStatement ps = connection.prepareStatement("UPDATE userinfo " +
                    "SET password=?,nickname=?,age=? " +
                    "WHERE username=?,password=?");

            ps.setString(1,userInfo.getPassword());
            ps.setString(2,userInfo.getNickname());
            ps.setInt(3,userInfo.getAge());
            ps.setString(4,userInfo.getUsername());
            return ps.executeUpdate();
        } catch (SQLException e) {
            e.printStackTrace();
        }


        return 0;

    }
}
